<template>
  <div id='bug-setting'>
    <v-header title="基础设置" :saveShow="false" :showDownloadBtn="false"></v-header>
    <div style="height: calc(100% - 56px);padding: 10px">
      <el-row>
        <el-col :span="6">
          <div style="background: white">
            <!--左边导航栏-->
            <el-card>
              <div slot="header" class="clearfix">
                <span style="font-weight: bold">应用设置</span>
              </div>
              <div class="lists-info" :class="{'active':btn===1&&true}" @click="btn=1">
                <i class="iconfont icon-yingyong-yingyongxinxi"></i>
                应用信息

              </div>
              <div class="lists-info" :class="{'active':btn===2&&true}" @click="btn=2">
                <i class="iconfont icon-symbol"></i>
                传符号表

              </div>
              <div class="lists-info" :class="{'active':btn===3&&true}" @click="btn=3">
                <i class="iconfont icon-shujugailan"></i>
                版本库

              </div>
            </el-card>
          </div>
        </el-col>
        <el-col :span="18">
          <div style="margin-left: 10px;background:white;height: 100%">
            <!--右边显示内容栏-->
            <el-card>
              <div slot="header" class="clearfix">
                <span v-show="btn===1">应用信息</span>
                <span v-show="btn===2">传符号表</span>
                <span v-show="btn===3">版本库<el-button type="text" class="el-icon-plus"
                                                     @click="openVersionDialog">添加版本</el-button></span>
              </div>
              <!--应用信息-->
              <div class="sec-box" v-loading="loading">
                <div v-show="btn===1" style="padding: 0 15px" v-if="ruleForm !== null">
                  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                    <el-row>
                      <p style="text-align: center;font-size: 24px;margin-bottom: 30px">
                        <template v-if="ruleForm.app_type === '0'">
                          <i style="font-size: 27px" class="iconfont icon-iOS"></i>
                          <!--<i style="font-size: 27px;position: relative;bottom: 2px" class="iconfont icon-iOS"></i>-->
                          <span>IOS</span>
                        </template>
                        <template v-if="ruleForm.app_type === '1'">
                          <i style="font-size: 27px" class="iconfont icon-anzhuo"></i>
                          <!--<i style="font-size: 27px;position: relative;bottom: 2px" class="iconfont icon-iOS"></i>-->
                          <span>Android</span>
                        </template>
                      </p>
                    </el-row>
                    <el-row>
                      <el-col :span="12" :offset="6">
                        <el-form-item label="应用名称" prop="app_name">
                          <el-input placeholder="请输入应用名称" v-model="ruleForm.app_name"
                                    @keyup.native.enter="submitForm('ruleForm')"></el-input>
                        </el-form-item>
                        <el-form-item label="创建时间">
                          <el-input placeholder="2018-04-20 09:28:17" v-model="ruleForm.app_create_time"
                                    :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="所属公司">
                          <el-input placeholder="深圳科蓝金信科技发展有限公司" v-model="ruleForm.app_own" :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="App Key">
                          <el-input placeholder="5fddfdc424a4e989f11e2e3439fba26c" v-model="ruleForm.app_id"
                                    :disabled="true"></el-input>
                        </el-form-item>
                        <!-- <el-form-item label="应用图标">
                            <p>建议尺寸 1024*1024，小于 5 MB</p>
                            <div>
                                <el-upload
                                    class="avatar-uploader"
                                    accept="jpg,png,jpeg"
                                    action="https://jsonplaceholder.typicode.com/posts/"
                                    :show-file-list="false"
                                    :on-success="handleAvatarSuccess"
                                    :before-upload="beforeAvatarUpload">
                                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                            </div>
                        </el-form-item> -->
                        <el-form-item>
                          <p>
                            <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                          </p>
                          <p>
                            <el-button type="danger" @click="deleteApp">删除应用</el-button>
                          </p>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </div>
                <!--传符号表-->
                <div v-show="btn===2" class="sign" style="padding: 0 15px">
                  <!--
                  <div class="symbol-setup mb20">
                    <div class="title1"> 通过配置自动上传符号表</div>
                    <div class="content">
                      <p class="mb20">
                        1、需要配置全局
                        <span class="cmd">buildscript dependency</span>
                      </p>
                      <div class="code" style="font-size: 14px">
                        <div class="shell hidden-y">
                          <div><span>buildscript {</span></div>
                          <div><span>&nbsp;&nbsp;dependencies {</span></div>
                          <div>
                            <span>&nbsp;&nbsp;&nbsp;&nbsp;classpath 'com.bugtags.library:bugtags-gradle:latest.integration'</span>
                            <span class="cmn">// 新增</span>
                          </div>
                          <div><span>&nbsp;&nbsp;}</span></div>
                          <div><span>}</span></div>
                        </div>
                      </div>
                      <p class="mb20 mt20">
                        2、需要配置
                        <span class="cmd">module</span>的<span class="cmd">build.gradle
                                        </span>
                      </p>
                      <div class="code" style="font-size: 14px">
                        <div class="shell hidden-y">
                          <div><span>apply plugin: 'com.bugtags.library.plugin'</span>
                          </div>
                          <div><span class="cmn">// 必须配置，否则自动上传不会生效</span></div>
                          <div><span>bugtags {</span></div>
                          <div><span>&nbsp;&nbsp;appKey '5fddfdc424a4e989f11e2e3439fba26c' </span>
                            <span class="cmn">// 这里是你的 appKey</span></div>
                          <div><span>&nbsp;&nbsp;appSecret 'APP_SECRET'</span> <span
                              class="cmn">// 这里是你的 appSecret，管理员在设置页可以查看</span></div>
                          <div><span>}</span></div>
                        </div>
                      </div>
                      <p style="margin:15px 0 0">
                        <a target="_blank" style="color:#2196f3"
                           href="https://docs.bugtags.com/zh/symbols/android/autoupload.html">查看详细说明</a>
                      </p></div>
                    <div style="text-align: center;margin:30px 0;"> 或手动上传符号表</div>
                  </div>
                  <div class="mb20"> 上传相应版本的符号表（建议压缩为 zip 格式上传），系统将会自动与崩溃问题相匹配。
                                    <a style="color:#2196f3;font-size: 13px"
                                       href="https://docs.bugtags.com/zh/symbols/android/find.html" target="_blank">如何获取符号表？</a>
                  </div>
                  -->
                  <div id="symbol-upload">
                    <el-table
                        :data="tableData"
                        style="width: 100%">
                      <el-table-column prop="ver_num" label="版本号"></el-table-column>
                      <el-table-column label="版本描述" prop="ver_desc"></el-table-column>
                      <!--<el-table-column prop="fileName" label="名称"></el-table-column>-->
                      <!--<el-table-column prop="upLoadTime" label="上传时间"></el-table-column>-->
                      <el-table-column label="操作">
                        <template slot-scope="scope">
                          <!--<span v-if="scope.row.fileName && scope.row.upLoadTime"
                                class="up-sign cursor" @click="deleteFile(scope.row)">删除符号表</span>-->
                          <span v-if="scope.row.is_exist === '1'"
                                class="up-sign cursor" @click="deleteFile(scope.row)">删除符号表</span>
                          <span v-else class="up-sign cursor" @click="upLoadFile(scope)">上传符号表</span>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
                <div v-show="btn===3" style="padding-left: 15px">
                  <div class="version-list" v-if="tableData && tableData.length > 0">
                    <el-table :data="tableData" :show-header="true">
                      <!-- <el-table-column type="selection" :selectable="handleSelected"></el-table-column> -->
                      <el-table-column label="">
                        <template slot-scope="scope">
                          <el-checkbox :checked="scope.row.ver_select === '1' ? true:false"
                                       @change="handleSelected($event, scope.row.ver_id)"></el-checkbox>
                        </template>
                      </el-table-column>
                      <el-table-column label="版本号" prop="ver_num"></el-table-column>
                      <el-table-column label="版本描述" prop="ver_desc"></el-table-column>
                      <el-table-column label="发布日期" prop="ver_release"></el-table-column>
                      <el-table-column label="操作">
                        <template slot-scope="scope">
                          <el-button type="text" size="mini" @click="deleteVersion(scope.row)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                  <div class="no_record" v-else>
                    <span>暂无数据哦</span>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
    <!--上传文件的弹框-->
      <el-dialog title="传符号表" :visible.sync="dialogVisible">
         <el-upload
             ref="upload"
             class="avatar-uploader"
             action="/bug/uploadMappingFile.action"
             :limit="1"
             :data="fileData"
             :show-file-list="true"
             :auto-upload="false"
             :file-list="fileList"
             :on-success="handleAvatarSuccess"
             :on-error="handleAvatarError"
             :before-upload="beforeAvatarUpload1">
           <P class="btn-upload up-btn">选取文件</P>
           <span class="btn-upload" style="top:60%">文件大小不超过 20 MB</span>
         </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelUpload">取 消</el-button>
          <!--<el-button type="primary">开始上传符号表</el-button>-->
          <el-button type="primary" @click="submitUpload">开始上传符号表</el-button>
        </div>
     </el-dialog>
    <!-- 添加版本弹窗 -->
    <el-dialog :visible.sync="isOpenVDialog" title="添加版本" class="add-ver-box" @close="cancel">
      <el-form :model="verForm" ref="versionForm" :rules="versionRule">
        <el-form-item prop="ver_num">
          <el-input placeholder="版本号" v-model="verForm.ver_num" @keyup.native.enter="addVersion"></el-input>
        </el-form-item>
        <el-form-item prop="ver_desc">
          <el-input placeholder="版本描述" v-model="verForm.ver_desc" @keyup.native.enter="addVersion"></el-input>
        </el-form-item>
        <el-form-item prop="ver_release">
          <el-date-picker
              v-model="verForm.ver_release"
              type="date"
              :clearable="false"
              value-format="yyyy-MM-dd"
              placeholder="发布日期"
              popper-class="zIndex-popper">
          </el-date-picker>
          <!--<el-input placeholder="发布日期" v-model="verForm.ver_release" @keyup.native.enter="addVersion"></el-input>-->
        </el-form-item>
        <el-form-item>
          <div class="btn-groups">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="addVersion">保存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script type='text/ecmascript-6'>
  import {VHeader} from './../../components'
  import api from '../../api/url'
  import {nextPage} from '../../assets/js/index'
  import {mixinParams} from '../../assets/js/mixin1'
  import ajax from '../../api/ajax/ajax'
  export default {
    components: {
      VHeader
    },
    mixins: [mixinParams],
    data () {
      return {
        btn: 1,
        tabsItem: 1,
        dialogVisible: false,
        imageUrl: '',
        rowInfo: '',
        ruleForm: null,
        rules: {
          app_name: [
            {required: true, message: '请输入应用名称', trigger: 'blur'},
            {min: 1, max: 50, message: '应用名称不能为空且限 50 个字符', trigger: 'blur'}
          ]
        },
        verForm: {
          ver_num: '',
          ver_desc: '',
          ver_release: ''
        },
        versionRule: {
          ver_num: [
            {required: true, message: '请输入版本号', trigger: 'blur'}
          ],
          ver_desc: [
            {required: true, message: '请输入版本描述', trigger: 'blur'}
          ],
          ver_release: [
            {required: true, message: '请输入版本发布日期', trigger: 'blur'}
          ]
        },
        tableData: null,
        fileData: {},
        fileList: [],
        isOpenVDialog: false,
        isRowChecked: false,
        loading: true
        // currentAppId: ''
      }
    },
    watch: {
      appFlag: {
        handler: function (val) {
          if (val) {
            // this.currentAppId = this.appId
            this.updateAppStatus()
            this.appFlag = false
          }
        },
        deep: false
      },
      appObjFlag: {
        handler (val) {
          if (val) {
            this.ruleForm = JSON.parse(JSON.stringify(this.bugAppObj))
            this.appObjFlag = false
          }
        }
      }
    },
    methods: {
      // 文件上传成功钩子
      handleAvatarSuccess (response) {
        // 根据后台的返回数据结构
        // this.imageUrl = res[0].url
        if (response.data === 1) {
          this.$message({
            message: '上传成功！',
            type: 'success'
          })
          this.dialogVisible = false
          this.fileList = []
          this.queryVersionList()
        }
      },
      // 文件上传失败钩子
      handleAvatarError (err) {
        if (err.data !== 1) {
          this.$message({
            message: '上传失败！',
            type: 'error'
          })
        }
      },
      /**
       * 应用信息里的上传应用头像 只支持jpg、png 不可以超过5MB
       * @param file
       * @returns {Ident|string|*|boolean}
       * 函数如果返回false  直接中断上传
       */
    /*  beforeAvatarUpload (file) {
        let suffix = file.name.substr(file.name.lastIndexOf('.'))
        const isLt2M = file.size / 1024 / 1024 < 5
        if (suffix !== '.jpg' && suffix !== '.png' && suffix !== '.jpeg') {
          this.$message.error('上传头像图片只能是 JPG 和 PNG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 5MB!')
        }
        return suffix && isLt2M
      }, */
      // 点击上传符号表--弹出上传会话框
      upLoadFile (row) {
        this.fileData = {ver_id: row.row.ver_id}
        this.dialogVisible = true
        this.rowInfo = row.row
      },
      // 点击删除符号表
      deleteFile (row) {
        this.$confirm('是否确定删除符号表', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          let params = {ver_id: row.ver_id}
          ajax.post(api.CLEAR_MAPPING_FILE, params)
            .then(res => {
              if (res.data === 1) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
                row.fileName = ''
                row.upLoadTime = ''
                this.queryVersionList()
              }
            })
          }).catch(() => {})
      },
      /**
       * 传符号表的上传应用头像 只支持jpg、png 不可以超过5MB
       * @param file
       * @returns {Ident|string|*|boolean}
       * 函数如果返回false  直接中断上传
       */
      beforeAvatarUpload1 (file) {
        this.rowInfo.fileName = file.name
        let time = new Date(file.lastModified)
        let timeHMS = this.zeroPadding(time.getHours(), 2) + ':' + this.zeroPadding(time.getMinutes(), 2) + ':' + this.zeroPadding(time.getSeconds(), 2)
        let date = this.zeroPadding(time.getFullYear(), 4) + '-' + this.zeroPadding(time.getMonth() + 1, 2) + '-' + this.zeroPadding(time.getDate(), 2)
        this.rowInfo.upLoadTime = date + ' ' + timeHMS
        const isLt2M = file.size / 1024 / 1024 < 20
        if (!isLt2M) {
          this.$message.error('文件大小不可以超过 20 MB!')
        }
        return isLt2M
      },
      zeroPadding (num, digit) {
        let zero = ''
        for (var i = 0; i < digit; i++) {
          zero += '0'
        }
        return (zero + num).slice(-digit)
      },
      // 确定上传按钮
      submitUpload () {
        this.$refs.upload.submit()
      },
      // 取消上传按钮
      cancelUpload () {
        this.fileList = []
        this.dialogVisible = false
      },
      // 切换应用
      updateAppStatus () {
        ajax.post(api.UPDADE_APP_STATUS, {bug_app_id: this.bugAppId}).then(res => {
          this.queryAppInfo()
          this.queryVersionList()
        })
      },
      // 查询当前应用
      queryAppInfo () {
        ajax.post(api.SELECT_APP).then(res => {
          if (res.data && res.data !== '') {
              this.pd_updateBugAppId(res.data.app_id)
              this.pd_updateBugApp(res.data)
              this.loading = false
          } else {
              this.pd_updateBugApp(null)
              this.loading = false
          }
        })
      },
      // 修改当前应用
      modifyAppInfo () {
        let postData = {
          bug_app_id: this.ruleForm.app_id,
          app_name: this.ruleForm.app_name
        }
        let appObj1 = JSON.parse(JSON.stringify(this.ruleForm))
        ajax.post(api.UPDATE_APP, postData).then(res => {
          this.$message({
            type: 'success',
            message: '修改成功'
          })
          this.resetForm('ruleForm')
          this.pd_updateBugApp(appObj1)
        })
      },
      // 删除当前应用
      deleteApp () {
        this.$confirm('确认删除该应用？').then(() => {
          ajax.post(api.DELETE_APP, {bug_app_id: this.bugAppId}).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.resetForm('ruleForm')
            this.ruleForm = null
            this.pd_updateBugAppId('')
            nextPage('/home/bugIndex', '')
            this.pd_updatePath('/home/bugIndex')
          })
        })
      },
      // 提交修改应用
      submitForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.modifyAppInfo()
          } else {
            return false
          }
        })
      },
      // 重置表单和检验
      resetForm (formName) {
        this.$refs[formName].resetFields()
      },
      // 处理版本选中状态
      handleSelected (checked, verId) {
        this.isRowChecked = checked
        this.updateVersionStatus(verId)
      },
      // 更新版本状态
      updateVersionStatus (verId) {
        let postData = {
          ver_id: verId,
          ver_select: this.isRowChecked ? '1' : '0'
        }
        ajax.post(api.UPDATE_APP_VERSION_STATUS, postData).then(res => {
          if (this.isRowChecked) {
            this.$message({
              type: 'success',
              message: '已选中记录'
            })
          } else {
            this.$message({
              type: 'success',
              message: '已取消选中记录'
            })
          }
        })
      },
      // 打开添加版本号的弹窗
      openVersionDialog () {
        this.isOpenVDialog = true
      },
      // 取消添加版本
      cancel () {
        this.isOpenVDialog = false
        this.resetForm('versionForm')
        this.verForm = {
          ver_num: '',
          ver_desc: '',
          ver_release: ''
        }
      },
      // 查询版本列表
      queryVersionList () {
        let params = {
          ver_select: ''
        }
        ajax.post(api.SELECT_APP_VERSION_LIST, params).then(res => {
          this.tableData = res.data.list
        })
      },
      // 添加版本
      addVersion () {
        this.$refs.versionForm.validate((valid) => {
          if (valid) {
            ajax.post(api.INSERT_APP_VERSION, this.verForm).then(res => {
              this.cancel()
              this.$message({
                type: 'success',
                message: '添加成功'
              })
              this.queryVersionList()
            })
          } else {
            return false
          }
        })
      },
      // 删除版本
      deleteVersion (row) {
        this.$confirm('确认删除该版本号？').then(() => {
          let params = {
            ver_id: row.ver_id
          }
          ajax.post(api.DELETE_APP_VERSION, params).then(res => {
            this.queryVersionList()
            this.$message({
              type: 'success',
              message: '已删除记录'
            })
          })
        })
      }
    },
    mounted () {
    },
    created () {
      this.updateAppStatus()
    }
  }
</script>
<style lang='stylus' rel='stylesheet/stylus' type="text/stylus">
  #bug-setting
    height 100%
    .sec-box
      min-height 100px
    .el-card__header
      padding 10px 20px
      position relative
      .el-button
        position absolute
        font-size 13px
        right 20px
        top 0
    .el-card__body
      padding 0
    .el-row, .el-col-18, .el-card
      height 100%
    .lists-info
      padding 8px 20px
      i
        vertical-align middle
        font-size 20px
        margin-right 5px
    .el-card__body
      height calc(100% - 42px)
      overflow-y auto
    .lists-info:hover
      background #f7f7f7
    .active
      background #F4F4F4 !important
    .demo-ruleForm
      .el-form-item__label:before
        content ''
      .el-form-item__content
        margin-left 110px !important
        p button
          width 220px
          margin-top 30px
      .el-input__inner
        border none
        border-bottom 1px solid #dcdfe6
        border-radius 0
        padding-left 0
      .el-input__inner:focus
        border-color #016DFB
      .el-form-item.is-success .el-input__inner
        border-color #67c23a
      .el-form-item.is-error .el-input__inner
        border-color #f56c6c
      .el-form-item__content
        font-size 13px !important
      .el-input.is-disabled .el-input__inner
        background white
        font-size 13px !important
        color #000
    .owner
      display inline-block
      width 28px
      height 28px
      border-radius 50%
      overflow hidden
      vertical-align middle
    .avatar-uploader .el-upload
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    .avatar-uploader .el-upload:hover
      border-color: #016DFB;
    .avatar-uploader-icon
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    .avatar
      width: 178px;
      height: 178px;
      display: block;
    .sign
      font-family 'Helvetica Neue', 'Hiragino Sans GB', 'WenQuanYi Micro Hei', 'Microsoft Yahei', sans-serif !important
    .symbol-setup
      font-size 13px
      .title1
        text-align center
        margin-bottom 25px
      .content
        border 1px solid #F0F0F0
        padding 15px
      .code
        position relative
        width 100%
        padding 10px
        padding-left 23px
        background-color #f5f5f5
        font-family Monaco, Menlo, Consolas, 'Courier New', monospace !important
      .cmn
        color #4caf50
    .el-table
      font-size 13px
    .up-sign
      color #2196f3
    .up-sign:hover
      color #0a6ebd
    .el-dialog
      width 600px
      .el-icon-close
        font-size 24px
    .el-dialog__body .el-upload
      width 548px
      height 200px
      border-width 2px
    .btn-upload
      position absolute
      top 38%
      left 50%
      margin-left -100px
      width 200px
      height 40px
      line-height 40px
    .up-btn
      box-shadow 0 2px 5px 0 rgba(0, 0, 0, .16), 0 2px 10px 0 rgba(0, 0, 0, .12)
    .el-upload--text:hover .up-btn
      background-color #007feb
      color #fff
    .el-collapse-item
      .el-checkbox
        margin-right 5px
    .add-ver-box
      .el-dialog__body
        padding 10px 20px 20px
        .btn-groups
          margin-top 20px
          text-align right
          .el-button
            width 100px
        .el-form-item
          margin-bottom 20px
          .el-input
            border-bottom 1px solid #eee
            height 39px
            position relative
            input
              display block
              width 100%
              height 38px
              padding 6px 0
              line-height 24px
              border 0 none
            &:after
              content ''
              display block
              position absolute
              left 0
              right 100%
              height 1px
              bottom 0
              transition right .3s linear
          .el-date-editor
            width 100% !important
          .el-input__prefix
            display none
          .el-input__suffix
            display none
          .el-form-item__error
            line-height 19px
          &.is-error
            .el-input
              &:after
                right 0
                background #f56c6c
          &.is-success
            .el-input
              &:after
                right 0
                background #016DFB
    .version-list
      li
        height 36px
        line-height 36px
        border-bottom 1px solid #ebeef5
        cursor pointer
        &:last-child
          border-bottom 0 none
        &.active
          background #fff !important
    .no_record
      padding 20px
      span
        display block
        line-height 48px
        height 48px
        font-size 14px
        color #999
        text-align center
        position relative
        &:before
          content '\e658'
          display inline-block
          vertical-align top
          height 48px
          font-size 48px
          margin-right 5px
          color #999
          font-family 'iconfont'
</style>
